<!DOCTYPE html>
<html lang="en">
<head>
  <title>Using the file system with Vert.x - Vert.x</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <meta content="Vert.x is a tool-kit for building reactive applications on the JVM." name="description">
  <link href="http://vertx.io/stylesheets/docs.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/stylesheets/font-awesome.min.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/javascripts/styles/rainbow.min.css" media="screen" rel="stylesheet">
  <!-- IE 6-8 support of HTML 5 elements -->
  <!--[if lt IE 9]>
  <script src="http://static.jboss.org/theme/js/libs/html5/pre3.6/html5.min.js"></script>
  <![endif]-->

  <link rel="apple-touch-icon" sizes="57x57" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="http://vertx.io/assets/favicons/vertx-favicon-7/manifest.json">
  <link rel="mask-icon" href="http://vertx.io/assets/favicons/vertx-favicon-7/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#7d3194">
  <meta name="msapplication-TileImage" content="http://vertx.io/assets/favicons/vertx-favicon-7/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link href="http://fonts.googleapis.com/css?family=Ubuntu:400,500,700,400italic" rel="stylesheet" type="text/css">
  <link rel="alternate" type="application/rss+xml" title="RSS"
     href="http://vertx.io/feed.xml">
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-30144458-1', 'auto');
    ga('create', 'UA-71153120-1', 'auto', 'tracker');
    ga('send', 'pageview');
    ga('tracker.send', 'pageview');
  </script>
</head>
<body>

<a href="http://www.reactivemanifesto.org/" id="reactive-manifesto-banner">
  <img style="border: 0; position: fixed; right: 0; top:0; z-index: 9000"
    src="http://d379ifj7s9wntv.cloudfront.net/reactivemanifesto/images/ribbons/we-are-reactive-black-right.png">
</a>

<a id="skippy" class="sr-only sr-only-focusable" href="#content"><div class="container"><span class="skiplink-text">Skip to main content</span></div></a>

<header class="navbar navbar-default navbar-static-top" id="top" role="banner">
  <div class="container">
    <div class="navbar-header">
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#vertx-navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="http://vertx.io/" class="navbar-brand"><img alt="Brand" src="http://vertx.io/assets/logo-sm.png"></a>
    </div>
    <nav class="collapse navbar-collapse" id="vertx-navbar-collapse">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="http://vertx.io/download/">Download</a></li>
        <li><a href="http://vertx.io/docs/">Documentation</a></li>
        <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
        <li><a href="http://vertx.io/community/">Community</a></li>
        <li><a href="http://vertx.io/materials/">Materials</a></li>
        <li><a href="http://vertx.io/blog/">Blog</a></li>        
      </ul>
    </nav>
  </div>
</header>



  <div class="page-header" id="content">
    <div class="container">
      <div class="row">
        <div class="col-sm-12">
          <h1>Using the file system with Vert.x</h1>
          
        </div>
      </div>
    </div>
  </div>




<div id="content">
  <div class="container docs-content">
    <div class="row">
      <div class="col-sm-12 col-md-push-9 col-md-3 hidden-xs hidden-sm">
        <div id="sidebar" data-spy="affix">
          <ul class="sectlevel1">
<li><a href="#_using_the_file_system_with_vert_x">Using the file system with Vert.x</a>
<ul class="sectlevel2">
<li><a href="#_asynchronous_files">Asynchronous files</a></li>
</ul>
</li>
</ul>
        </div>
      </div>
      <div class="col-sm-12 col-md-pull-3 col-md-9">
        <div class="toc hidden-md hidden-lg">
          <h2>Table of Contents</h2>
          <ul class="sectlevel1">
<li><a href="#_using_the_file_system_with_vert_x">Using the file system with Vert.x</a>
<ul class="sectlevel2">
<li><a href="#_asynchronous_files">Asynchronous files</a></li>
</ul>
</li>
</ul>
        </div>
        <div class="sect1">
<h2 id="_using_the_file_system_with_vert_x">Using the file system with Vert.x</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The Vert.x <code><a href="../../groovydoc/io/vertx/groovy/core/file/FileSystem.html">FileSystem</a></code> object provides many operations for manipulating the file system.</p>
</div>
<div class="paragraph">
<p>There is one file system object per Vert.x instance, and you obtain it with  <code><a href="../../groovydoc/io/vertx/groovy/core/Vertx.html#fileSystem()">fileSystem</a></code>.</p>
</div>
<div class="paragraph">
<p>A blocking and a non blocking version of each operation is provided. The non blocking versions take a handler
which is called when the operation completes or an error occurs.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of an asynchronous copy of a file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">def fs = vertx.fileSystem()

// Copy file from foo.txt to bar.txt
fs.copy("foo.txt", "bar.txt", { res -&gt;
  if (res.succeeded()) {
    // Copied ok!
  } else {
    // Something went wrong
  }
})</code></pre>
</div>
</div>
<div class="paragraph">
<p>The blocking versions are named <code>xxxBlocking</code> and return the results or throw exceptions directly. In many
cases, depending on the operating system and file system, some of the potentially blocking operations can return
quickly, which is why we provide them, but it&#8217;s highly recommended that you test how long they take to return in your
particular application before using them from an event loop, so as not to break the Golden Rule.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s the copy using the blocking API:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">def fs = vertx.fileSystem()

// Copy file from foo.txt to bar.txt synchronously
fs.copyBlocking("foo.txt", "bar.txt")</code></pre>
</div>
</div>
<div class="paragraph">
<p>Many operations exist to copy, move, truncate, chmod and many other file operations. We won&#8217;t list them all here,
please consult the <code><a href="../../groovydoc/io/vertx/groovy/core/file/FileSystem.html">API docs</a></code> for the full list.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s see a couple of examples using asynchronous methods:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">import io.vertx.groovy.core.Vertx
import io.vertx.groovy.core.buffer.Buffer
def vertx = Vertx.vertx()

// Read a file
vertx.fileSystem().readFile("target/classes/readme.txt", { result -&gt;
  if (result.succeeded()) {
    println(result.result())
  } else {
    System.err.println("Oh oh ...${result.cause()}")
  }
})

// Copy a file
vertx.fileSystem().copy("target/classes/readme.txt", "target/classes/readme2.txt", { result -&gt;
  if (result.succeeded()) {
    println("File copied")
  } else {
    System.err.println("Oh oh ...${result.cause()}")
  }
})

// Write a file
vertx.fileSystem().writeFile("target/classes/hello.txt", Buffer.buffer("Hello"), { result -&gt;
  if (result.succeeded()) {
    println("File written")
  } else {
    System.err.println("Oh oh ...${result.cause()}")
  }
})

// Check existence and delete
vertx.fileSystem().exists("target/classes/junk.txt", { result -&gt;
  if (result.succeeded() &amp;&amp; result.result()) {
    vertx.fileSystem().delete("target/classes/junk.txt", { r -&gt;
      println("File deleted")
    })
  } else {
    System.err.println("Oh oh ... - cannot delete the file: ${result.cause()}")
  }
})</code></pre>
</div>
</div>
<div class="sect2">
<h3 id="_asynchronous_files">Asynchronous files</h3>
<div class="paragraph">
<p>Vert.x provides an asynchronous file abstraction that allows you to manipulate a file on the file system.</p>
</div>
<div class="paragraph">
<p>You open an <code><a href="../../groovydoc/io/vertx/groovy/core/file/AsyncFile.html">AsyncFile</a></code> as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">def options = [:]
fileSystem.open("myfile.txt", options, { res -&gt;
  if (res.succeeded()) {
    def file = res.result()
  } else {
    // Something went wrong!
  }
})</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>AsyncFile</code> implements <code>ReadStream</code> and <code>WriteStream</code> so you can <em>pump</em>
files to and from other stream objects such as net sockets, http requests and responses, and WebSockets.</p>
</div>
<div class="paragraph">
<p>They also allow you to read and write directly to them.</p>
</div>
<div class="sect3">
<h4 id="_random_access_writes">Random access writes</h4>
<div class="paragraph">
<p>To use an <code>AsyncFile</code> for random access writing you use the
<code><a href="../../groovydoc/io/vertx/groovy/core/file/AsyncFile.html#write(io.vertx.core.buffer.Buffer,%20long,%20io.vertx.core.Handler)">write</a></code> method.</p>
</div>
<div class="paragraph">
<p>The parameters to the method are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>buffer</code>: the buffer to write.</p>
</li>
<li>
<p><code>position</code>: an integer position in the file where to write the buffer. If the position is greater or equal to the size
of the file, the file will be enlarged to accommodate the offset.</p>
</li>
<li>
<p><code>handler</code>: the result handler</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Here is an example of random access writes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">import io.vertx.groovy.core.Vertx
import io.vertx.groovy.core.buffer.Buffer
def vertx = Vertx.vertx()
vertx.fileSystem().open("target/classes/hello.txt", [:], { result -&gt;
  if (result.succeeded()) {
    def file = result.result()
    def buff = Buffer.buffer("foo")
    for (def i = 0;i &lt; 5;i++) {
      file.write(buff, buff.length() * i, { ar -&gt;
        if (ar.succeeded()) {
          println("Written ok!")
          // etc
        } else {
          System.err.println("Failed to write: ${ar.cause()}")
        }
      })
    }
  } else {
    System.err.println("Cannot open file ${result.cause()}")
  }
})</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_random_access_reads">Random access reads</h4>
<div class="paragraph">
<p>To use an <code>AsyncFile</code> for random access reads you use the
<code><a href="../../groovydoc/io/vertx/groovy/core/file/AsyncFile.html#read(io.vertx.core.buffer.Buffer,%20int,%20long,%20int,%20io.vertx.core.Handler)">read</a></code>
method.</p>
</div>
<div class="paragraph">
<p>The parameters to the method are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>buffer</code>: the buffer into which the data will be read.</p>
</li>
<li>
<p><code>offset</code>: an integer offset into the buffer where the read data will be placed.</p>
</li>
<li>
<p><code>position</code>: the position in the file where to read data from.</p>
</li>
<li>
<p><code>length</code>: the number of bytes of data to read</p>
</li>
<li>
<p><code>handler</code>: the result handler</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of random access reads:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">import io.vertx.groovy.core.Vertx
import io.vertx.groovy.core.buffer.Buffer
def vertx = Vertx.vertx()
vertx.fileSystem().open("target/classes/les_miserables.txt", [:], { result -&gt;
  if (result.succeeded()) {
    def file = result.result()
    def buff = Buffer.buffer(1000)
    for (def i = 0;i &lt; 10;i++) {
      file.read(buff, i * 100, i * 100, 100, { ar -&gt;
        if (ar.succeeded()) {
          println("Read ok!")
        } else {
          System.err.println("Failed to write: ${ar.cause()}")
        }
      })
    }
  } else {
    System.err.println("Cannot open file ${result.cause()}")
  }
})</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_opening_options">Opening Options</h4>
<div class="paragraph">
<p>When opening an <code>AsyncFile</code>, you pass an <code><a href="../dataobjects.html#OpenOptions">OpenOptions</a></code> instance.
These options describe the behavior of the file access. For instance, you can configure the file permissions with the
<code><a href="../dataobjects.html#OpenOptions#setRead(boolean)">read</a></code>, <code><a href="../dataobjects.html#OpenOptions#setWrite(boolean)">write</a></code>
and <code><a href="../dataobjects.html#OpenOptions#setPerms(java.lang.String)">perms</a></code> methods.</p>
</div>
<div class="paragraph">
<p>You can also configure the behavior if the open file already exists with
<code><a href="../dataobjects.html#OpenOptions#setCreateNew(boolean)">createNew</a></code> and
<code><a href="../dataobjects.html#OpenOptions#setTruncateExisting(boolean)">truncateExisting</a></code>.</p>
</div>
<div class="paragraph">
<p>You can also mark the file to be deleted on
close or when the JVM is shutdown with <code><a href="../dataobjects.html#OpenOptions#setDeleteOnClose(boolean)">deleteOnClose</a></code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_flushing_data_to_underlying_storage">Flushing data to underlying storage.</h4>
<div class="paragraph">
<p>In the <code>OpenOptions</code>, you can enable/disable the automatic synchronisation of the content on every write using
<code><a href="../dataobjects.html#OpenOptions#setDsync(boolean)">dsync</a></code>. In that case, you can manually flush any writes from the OS
cache by calling the <code><a href="../../groovydoc/io/vertx/groovy/core/file/AsyncFile.html#flush()">flush</a></code> method.</p>
</div>
<div class="paragraph">
<p>This method can also be called with an handler which will be called when the flush is complete.</p>
</div>
</div>
<div class="sect3">
<h4 id="_using_asyncfile_as_readstream_and_writestream">Using AsyncFile as ReadStream and WriteStream</h4>
<div class="paragraph">
<p><code>AsyncFile</code> implements <code>ReadStream</code> and <code>WriteStream</code>. You can then
use them with a <em>pump</em> to pump data to and from other read and write streams. For example, this would
copy the content to another <code>AsyncFile</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-groovy" data-lang="groovy">import io.vertx.groovy.core.Vertx
import io.vertx.groovy.core.streams.Pump
def vertx = Vertx.vertx()
def output = vertx.fileSystem().openBlocking("target/classes/plagiary.txt", [:])

vertx.fileSystem().open("target/classes/les_miserables.txt", [:], { result -&gt;
  if (result.succeeded()) {
    def file = result.result()
    Pump.pump(file, output).start()
    file.endHandler({ r -&gt;
      println("Copy done")
    })
  } else {
    System.err.println("Cannot open file ${result.cause()}")
  }
})</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also use the <em>pump</em> to write file content into HTTP responses, or more generally in any
<code>WriteStream</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="classpath">Accessing files from the classpath</h4>
<div class="paragraph">
<p>When vert.x cannot find the file on the filesystem it tries to resolve the
file from the class path. Note that classpath resource paths never start with
a <code>/</code>.</p>
</div>
<div class="paragraph">
<p>Due to the fact that Java does not offer async access to classpath
resources, the file is copied to the filesystem in a worker thread when the
classpath resource is accessed the very first time and served from there
asynchrously. When the same resource is accessed a second time, the file from
the filesystem is served directly from the filesystem. The original content
is served even if the classpath resource changes (e.g. in a development
system).</p>
</div>
<div class="paragraph">
<p>This caching behaviour can be disabled by setting the system
property <code>vertx.disableFileCaching</code> to <code>true</code>. The path where the files are
cached is <code>.vertx</code> by default and can be customized by setting the system
property <code>vertx.cacheDirBase</code>.</p>
</div>
<div class="paragraph">
<p>The whole classpath resolving feature can be disabled by setting the system
property <code>vertx.disableFileCPResolving</code> to <code>true</code>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
these system properties are evaluated once when the the <code>io.vertx.core.impl.FileResolver</code> class is loaded, so
these properties should be set before loading this class or as a JVM system property when launching it.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_closing_an_asyncfile">Closing an AsyncFile</h4>
<div class="paragraph">
<p>To close an <code>AsyncFile</code> call the <code><a href="../../groovydoc/io/vertx/groovy/core/file/AsyncFile.html#close()">close</a></code> method. Closing is asynchronous and
if you want to be notified when the close has been completed you can specify a handler function as an argument.</p>
</div>
</div>
</div>
</div>
</div>

        

        
          <div id="footer">
            <div id="footer-text">
              
                Last updated 2016-09-12 08:38:04 CEST
              
              
            </div>
          </div>
        
      </div>
    </div>
  </div>
</div>

<footer>
  <div class="container">
    <div class="row">
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Vert.x</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/">Home</a></li>
          <li><a href="http://vertx.io/download/">Download</a></li>
          <li><a href="http://vertx.io/docs/">Documentation</a></li>
          <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
          <li><a href="http://vertx.io/blog/">Blog</a></li>
          <li><a href="http://vertx.io/vertx2/" class="vertx-2-link">Vert.x 2</a></li>
        </ul>
      </div>
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Community</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/community/">Help &amp; Contributors</a></li>
          <li><a href="http://vertx.io/materials/">Learning materials</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx">User Group</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx-dev">Developer Group</a></li>
        </ul>
      </div>

      <div class="col-xs-12 col-sm-6 col-lg-offset-2 col-md-6 copyright">
        <p>Vert.x is open source and dual licensed under the <a href="https://www.eclipse.org/org/documents/epl-v10.php">Eclipse Public License 1.0</a> and <a href="https://www.apache.org/licenses/LICENSE-2.0.html">Apache License 2.0</a>.</p>
        <p>This website is licensed under the <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC BY-SA 3.0 License</a>.<br>
        Design by <a href="http://www.michel-kraemer.com">Michel Kr&auml;mer</a>. <a href="http://www.entypo.com">Entypo pictograms</a> by Daniel Bruce.</p>
        <div class="row">
          <div class="col-xs-12 col-lg-offset-1 col-md-5">
            <a href="http://eclipse.org">
            <img class="logo eclipse-logo" src="http://vertx.io/assets/eclipse_logo_grey_small.png" width="204" height="48">
            </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-0 col-md-5">
            <a href="http://cloudbees.com">
            <img class="logo cloudbees-logo" src="http://vertx.io/assets/Button-Built-on-CB-1-grey.png" width="180" height="48">
           </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-1 col-md-5 jprofiler">
            <a href="http://www.ej-technologies.com/products/jprofiler/overview.html"
            style="text-decoration:none">
            <img class="logo jprofiler-logo" src="http://vertx.io/assets/jprofiler-logo.png" width="48" height="48"><span class="jprofiler-logo">&nbsp; JPROFILER</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</footer>

<script src="http://static.jboss.org/theme/js/libs/jquery/jquery-1.9.1.min.js"></script>
<script src="http://vertx.io/javascripts/bootstrap.min.js"></script>
<script src="http://vertx.io/javascripts/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>



<script src="http://vertx.io/javascripts/sidebar.js"></script>


</body>
</html>
